"use strict";
const recycleTime = 10000;

class MsgNotifyUtil {

  timeout = null;
  intervalId = null;

  record = {};


  /**
   * 添加回调
   * @param topic
   * @param callbackFunction
   */
  addCallbackFunction(topic, callbackFunction, timeoutCallBackFunction) {
    let array = this.record[topic];
    if (!array) {
      array = [];
      this.record[topic] = array;
    }
    array.push({callback: callbackFunction, timestamp: new Date().getTime(), timeoutCallBack: timeoutCallBackFunction})
  }

  /**
   * 通知回调
   * @param topic
   * @param data
   */
  notify(topic, data) {
    const array = this.record[topic];
    const nowTimestamp = new Date().getTime();
    if (array) {
      for (const func of array) {
        let callback = func.callback;
        let timestamp = func.timestamp;
        if (nowTimestamp - timestamp <= this.timeout) {
          callback(data);
        } else if (func.timeoutCallBack) {
          func.timeoutCallBack();
        }
      }
    }
    delete this.record[topic];
  }


  /**
   * 设置回收超过时长的监听者
   * @param timeout
   */
  setRecycleTimeout = function (timeout) {
    if (this.timeout == timeout) {
      return;
    }
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
    const record = this.record;
    //如果有超时时长 回收已经超时的回调函数
    if (timeout) {
      this.intervalId = setInterval(() => {
        const nowTimestamp = new Date().getTime();
        for (let key in record) {
          const array = record[key];
          if (array) {
            for (let i = array.length - 1; i >= 0; i--) {
              const timestamp = array[i].timestamp;
              if ((nowTimestamp - timestamp) > timeout) {
                const splice = array.splice(i, 1);
                if (splice.timeoutCallBack) {
                  splice.timeoutCallBack();
                }
              }
            }
            if (array.length == 0) {
              delete this.record[key];
            }
          }
        }
      }, recycleTime);
    }
  }

  static guid = function () {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
}

export default MsgNotifyUtil;


// 测试用例 回收2-1 执行1-1,1-2
// let notifyUtil = new MsgNotifyUtil();
// notifyUtil.setRecycleTimeout(1000);
// notifyUtil.addCallbackFunction("1", (data) => {
//   console.log("1-1", data)
// });
// notifyUtil.addCallbackFunction("1", (data) => {
//   console.log("1-2", data)
// });
// notifyUtil.addCallbackFunction("2", (data) => {
//   console.log("2-1", data)
// });
// notifyUtil.notify("1", "x");
